App({
  globalData: {
    userInfo: null,
    NETWORK_LIB: '',
    isIphone: false,
    API_URL: 'https://api-kitap.qiyat.cn',
    // API_URL: 'http://127.0.0.1:3000',
    isVIPAuthority: false, // VIP权限
    vipDay: 0,
    isLittleDrawingVisible: false, // 播放最小画
    kitapCon: {}, // 书籍信息
    chapterName: '', // 章节名

    // 播放页面播放配置
    audioInfo: {
      isPlaying: false, // 是否正在播放
      playId: null,     // 当前音频 ID
      src: "",          // 音频地址
      currentTime: 0,    // 播放进度
      formattedDuration: '00:00', // 总时长
      bgAudio: null,
      speed: 1, // 倍速
      totalIndex: 1000, // 总 index
      playCurrentIndex: 99, // 当前播放音频 index
    },
    audioList : [], // 音频

    // 播放页面定时配置
    timingConif: {
      timingType: 2, // 定时类     集数定时、时间定时
      timingCheckedChange: false, // 定时开关
      timingTime: '', // 定时时间
      secondsNoFormat: 0,
      timingJi: -1, // 集数定时
    },
    
  },

  // 请求头配置：发起请求时添加该方法为参数
  header() {
    let userInfo = wx.getStorageSync('userInfo')
    let token = userInfo != null? userInfo.token:null
    let header = { "Content-Type": "application/json;charset=utf-8","token":token}
    // let sid = wx.getStorageSync('sid')
    // if (sid.length != 0) header['Cookie'] = sid
    return header
  },
  
  // 登录
  login(callback) {
    if (!callback) callback = function () {}
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      callback(userInfo)
      return
    }
    let code = null;
    wx.login({
      success(res) {
        if (res.code) code = res.code
      }
    })
    
    wx.getUserProfile({
      desc: '授权登录吧！',
      success: (res) => {
        wx.request({
          url: `${this.globalData.API_URL}/userLogin`,
          header: {
            'content-type': 'application/json'
          },
          method: 'post',
          data: {
            code: code,
            iv: res.iv,
            encryptedData: res.encryptedData
          },
          success: (res) =>{
            this.userInfo = res.data.user
            wx.setStorageSync('uid', res.data.user.id);
            wx.setStorage({
              key: "userInfo",
              data: res.data,
            })

            callback(res.data)
          },
          fail:err=>{
            console.log('err: ', err);
          }
        })
      },
      fail: err => {
        // 返回上页面
        // wx.navigateBack();
      }
    })
  },

  // 检查登录是否过期
  isOvedue() {
    let userInfo = wx.getStorageSync('userInfo')
    let user_id = userInfo.user.id

    if (user_id && user_id > 0) {
      wx.request({
        url: `${this.globalData.API_URL}/getFavorites`,
        data: { user_id },
        header: this.header(),
        method: 'post',
        success: function (res) {
          if (res.data.status == 523) {
            wx.setStorage({
              key: "userInfo",
              data: '',
            })
          }
        }
      })
    }
  },

  onLaunch() {
    this.getUserAuth(); // 获取权限

    // 获取机型信息
    const { platform } = wx.getDeviceInfo()
    const { statusBarHeight} = wx.getWindowInfo()
    const { top, height } = wx.getMenuButtonBoundingClientRect()
    
    // 判断是否苹果产品
    let DeviceInfo = wx.getDeviceInfo();
    const model = DeviceInfo.model.substring(0, 6)
    if (model == 'iPad' || model == 'iPhone') {
      this.globalData.isIphone = true
    }

    // 状态栏高度
    wx.setStorageSync('statusBarHeight', statusBarHeight)
    // 胶囊按钮高度 一般是32 如果获取不到就使用32
    wx.setStorageSync('menuButtonHeight', height ? height : 32)

    // 判断胶囊按钮信息是否成功获取
    if (top && top !== 0 && height && height !== 0) {
      const navigationBarHeight = (top - statusBarHeight) * 2 + height
      // 导航栏高度
      wx.setStorageSync('navigationBarHeight', navigationBarHeight)
    } else {
      wx.setStorageSync(
        'navigationBarHeight',
        platform === 'android' ? 48 : 40
      )
    }

    // 检查登录是否过期
    // this.isOvedue()

  },

  // 获取权限 
  getUserAuth() {
    let userInfo = wx.getStorageSync('userInfo');
    if(!userInfo) return this.login();
    let user_id = userInfo.user.id;
    let that = this;
    wx.request({
      url: `${this.globalData.API_URL}/getUserAuth`,
      method: 'POST',
      data: { user_id, user_id },
      success(res) {
        that.globalData.vipDay = res.data.vipTime;
        if(res.data.vipTime > 0) that.globalData.isVIPAuthority = true;
      },
    });
  },

  onShow() {
  },

  // 小程序退出时   
  onHide() {},

  // 更新播放状态
  updateAudioState(state) {
    console.log("state:: ", state)
    this.globalData.audioInfo = { ...this.globalData.audioInfo, ...state };
  }
})
